package com.dgl.sdk.util;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.widget.TextView;

import java.io.File;
import java.net.URL;

/**
 * Created by colin.ding on 2014/6/4.
 */

//让textView 显示html样式文字 可异步加载网络图片
public class TextViewWithImage {

    private Context context;
    private String imgCachDir;
    private String imgFilePath = "";
    private Html.ImageGetter imageGetter;

//    String sText = "测试图片信息：<br><img src=\"http://avatar.csdn.net/0/3/8/1_zhang957411207.jpg\" />";

    public TextViewWithImage(Context context, String imgCachDir){
        this.context = context;
        this.imgCachDir = imgCachDir;
    };

    public void show(final TextView textView, final String  text){

        if(!text.contains("<img src=")){
            textView.setText(text);
        }else{
            imageGetter = new Html.ImageGetter() {
                public Drawable getDrawable(String source) {
                    Drawable drawable = null;

                    File file = new File(imgFilePath);
                    if(file.exists()){
                        drawable = BitmapUtil.FiletoDrawable(imgFilePath);
                        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                    }else{
                        FileDownloader fd = new FileDownloader(context, source, imgCachDir, FileCache.urlToFileName(source),
                                1, new FileDownloader.DownloadCallback() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onProgress(int progress) {

                            }

                            @Override
                            public void onComplete(String filePath) {
                                imgFilePath = filePath;

                                textView.setText(Html.fromHtml(text, imageGetter, null));
                            }

                            @Override
                            public void onError(String error) {

                            }
                        });

                        fd.download();
                    }


                    return drawable;
                }
            };

            textView.setText(Html.fromHtml(text, imageGetter, null));
        }

    }
}
